import os
import threading
import queue

def multi_thread_stat(stat_dir):
    #结果记录在字典可变变量中，操作线程时传入，用于线程中数据的统计，解决多线程不能获取方法返回值的问题
    result = {'file_count': 0, 'total_code_line': 0}
    threads = []
    q = queue.Queue()
    lock = threading.Lock()

    if not os.path.exists(stat_dir):
        print("目录不存在")
        return False

    #由上层到下层取该目录下所有 根目录，文件夹，文件名
    for root, dirs, files in os.walk(stat_dir, topdown=False):
        for file in files:
            if file.endswith('.py'):
                result['file_count'] += 1
                file_path = os.path.join(root,file)
                q.put(file_path)

    #创建5个线程，分别取栈中的文件绝对路径，并计算该文件的代码量
    for i in range(5):
        threads.append(threading.Thread(target=stat_code_for_file, args=(q, lock, result)))

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    return result


def stat_code_for_file(q, lock, result):

    while not q.empty():
        file_path = q.get()
        with open(file_path,encoding='utf-8',errors='ignore') as f:
            for line in f:
                line = line.strip()

                if line == "":
                    continue

                lock.acquire()
                result['total_code_line'] += 1
                lock.release()

if __name__=="__main__":
    print(multi_thread_stat("D:\\python_train"))


